File Paths and Managing Files
File Paths
Understanding File Paths
File paths are specific locations of files on a computer or web server. They are crucial in programming for accessing, modifying, and organizing files within applications.
Types of File Paths
Relative File Paths
- Used to read and write files using the file name alone.
- Default to the directory where the Python script is executed.
- Preferred for their flexibility across different systems.
Absolute File Paths
- Specify the exact location of a file, including the drive name, directory, and file name.
- Vary between operating systems:
- Windows:
C:/my-directory/target-file.txt - Mac/Linux:
/users/username/my-directory/target-file.txt
- Windows:
- Generally avoided due to lack of portability.
Using File Paths in Python
- Cross-Platform Compatibility: Use the
os.pathmodule to handle differences between operating systems. - Environment Variables: File paths can also reference environment variables, libraries, and other resources.
How to Write File Paths in Code
File Paths and Operating Systems
- Windows:
- Uses drive letters and backslashes:
C:\my-directory\target-file.txt - Backslashes are special characters in Python and need to be escaped.
- Uses drive letters and backslashes:
- Mac/Linux:
- Use forward slashes and start from the root directory:
/users/username/my-directory/target-file.txt
- Use forward slashes and start from the root directory:
Best Practices
- Use Forward Slashes: Even on Windows, using forward slashes (
/) avoids issues with escape characters.- Example:
C:/my-directory/target-file.txt
- Example:
- Avoid Absolute Paths: Use relative paths or dynamically construct paths for portability.
The os Module in Python
- Accessing the Current Working Directory:
import oscurrent_directory = os.getcwd()
- Constructing File Paths:
file_path = os.path.join(current_directory, 'target-file.txt')
- Listing Files and Directories:
contents = os.listdir(current_directory)
Examples
Deleting a File
import os
# Delete a file
os.remove('obsolete-file.txt')
Renaming a File
import os
# Rename a file
os.rename('old-name.txt', 'new-name.txt')
Working with Files
File Operations with the os Module
- Deleting Files:
os.remove('filename') - Renaming Files:
os.rename('old_name', 'new_name') - Moving Files: Use
shutil.move('source', 'destination')from theshutilmodule.
Checking File Existence
- Using
os.path.exists():import osif os.path.exists('important-file.txt'):print('File exists.')else:print('File does not exist.')
More File Information
Getting File Metadata
- File Size:
import ossize = os.path.getsize('example.txt')print(f'File size: {size} bytes')
- Last Modification Time:
import osimport datetimetimestamp = os.path.getmtime('example.txt')modification_time = datetime.datetime.fromtimestamp(timestamp)print(f'Last modified: {modification_time}')
Working with Timestamps
- Unix Timestamps: Represent the number of seconds since January 1, 1970.
- Converting Timestamps:
import datetimetimestamp = 1609459200 # Example timestampreadable_time = datetime.datetime.fromtimestamp(timestamp)print(readable_time) # Outputs: 2021-01-01 00:00:00
Absolute Paths
- Getting Absolute Paths:
import osabsolute_path = os.path.abspath('relative/path/to/file.txt')print(absolute_path)